#include "TcpServer.hpp"
#include "Socket.hpp"
#include "Accepter.hpp"
#include <memory>
#include <iostream>

using namespace NetWorkModule;

static const int gbacklog = 32;

void Test(Connection *conn)
{
    std::cout << "get event, sockfd is : " << conn->SockFd() << std::endl;
}

void Usage(string process)
{
    cerr << "Usage: " << process << "port" << endl;
}

//Reactor : 反应堆模式,半同步半异步模式，Linux高并发服务器最常见的模式
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }

    int port = std::stoi(argv[1]);

    // 1.创建listensock
    std::unique_ptr<TcpSocket> listensock = std::make_unique<TcpSocket>();
    listensock->BuildListenSocketMethod(port, gbacklog);
    // 2. 创建tcpserver
    std::unique_ptr<TcpServer>
        svr = std::make_unique<TcpServer>();
    std::unique_ptr<Accepter> accepter = std::make_unique<Accepter>();
    auto listen_recver = std::bind(&Accepter::AccepterConnection, accepter.get(), std::placeholders::_1);
    // 3.

    // 4. 构建listen对应的connection, 添加到tcpserver中
    Connection *conn = ConnectionFactory::BuildListenConnection(
        listensock->GetSockFd(),listen_recver, EPOLLIN | EPOLLET, svr.get());
    svr->AddConnection(conn);

    // 5.开始事件派发
    svr->Dispatcher();
    return 0;
}